# app.py
import os
import logging
from logging import handlers
from flask import Flask
from flask_cors import CORS
from config import config
from api.database import engine
from api.models import Base


from api import register_bp, login_bp, getOne_bp, user_data_bp


def create_app(config_obj=config):
    app = Flask(__name__)

    app.config.from_object(config_obj)
    CORS(app, resources={r"/api/*": {"origins": app.config["CORS_ORIGINS"]}})

    if engine is not None:
        Base.metadata.create_all(bind=engine)
    else:
        print("数据库未配置，跳过自动建表")
    # 注册API蓝图
    app.register_blueprint(register_bp, url_prefix="/mytool")
    app.register_blueprint(login_bp, url_prefix="/mytool")
    app.register_blueprint(getOne_bp, url_prefix="/mytool")
    app.register_blueprint(user_data_bp, url_prefix="/mytool")

    setup_logging(app)

    return app


def setup_logging(app):
    log_file = app.config["LOG_FILE"]
    log_dir = os.path.dirname(log_file)
    log_level = app.config.get("LOG_LEVEL", logging.INFO)

    if not os.path.exists(log_dir):
        os.makedirs(log_dir, exist_ok=True)

    formatter = logging.Formatter(
        "%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]"
    )

    file_handler = handlers.RotatingFileHandler(
        log_file, maxBytes=10 * 1024 * 1024, backupCount=10, encoding="utf-8"
    )
    file_handler.setFormatter(formatter)
    file_handler.setLevel(log_level)

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    console_handler.setLevel(log_level)

    logger = app.logger
    logger.setLevel(log_level)
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    logger.info(" 应用已启动，日志配置完成")
